package com.itheima.service.impl;

import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;

import com.itheima.utils.DateUtils;

import org.apache.ibatis.annotations.Param;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    /**
     * 添加或编辑预约设置
     *
     * @param orderSetting
     */
    @Override
    public void editNumberByDate(OrderSetting orderSetting) throws Exception {
        //预约日期
        Date orderDate = orderSetting.getOrderDate();
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        String format = simpleDateFormat.format(orderDate);
        String date2String = DateUtils.parseDate2String(orderDate);
        Date date = DateUtils.parseString2Date(date2String);
        //可预约人数
        int number = orderSetting.getNumber();
        //根据日期查询数据，如果有数据则修改，没有则新增
//        OrderSetting oldOrderSetting = orderSettingDao.getByOrderDate(format);
        OrderSetting oldOrderSetting = orderSettingDao.getByOrderDate(date);
        if (oldOrderSetting != null) {
            //有，修改
            oldOrderSetting.setNumber(number);
            orderSettingDao.update(oldOrderSetting);
        } else {
            //没有，新增
            orderSetting.setReservations(0);
            orderSettingDao.save(orderSetting);
        }
    }
        @Override
        public List<Map> getOrderSettingByMonth (@Param("orderDate") String date){
            List<OrderSetting> orderSettingByMonth = orderSettingDao.getOrderSettingByMonth(date);
            List<Map> list = new ArrayList<>();
            for (OrderSetting orderSetting : orderSettingByMonth) {
                HashMap<String, Object> map = new HashMap<>();

                Date orderDate = orderSetting.getOrderDate();
                int number = orderSetting.getNumber();
                int reservations = orderSetting.getReservations();
                map.put("number", number);
                map.put("reservations", reservations);
                try {
                    String dayStr = DateUtils.parseDate2String(orderDate, "dd");
//                    Date date1 = DateUtils.parseString2Date(dayStr, "dd");
                    map.put("date",dayStr);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                list.add(map);
            }
            return list;


    }
}